package com.juyu.miliao.scheduler.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.common.constant.VipStatusType;
import com.juyu.miliao.common.constant.VipType;
import com.juyu.miliao.common.delay.DelayMessage;
import com.juyu.miliao.scheduler.dao.mysql.UserInfoDao;
import com.juyu.miliao.scheduler.dao.mysql.UserVipDao;
import com.juyu.miliao.scheduler.domin.User;
import com.juyu.miliao.scheduler.domin.UserVip;
import com.juyu.miliao.scheduler.handler.VipExpireQueueThread;
import com.juyu.miliao.scheduler.message.MakeFriendsMessage;
import com.juyu.miliao.scheduler.service.VipExpireService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sound.midi.SoundbankResource;
import java.time.Instant;
import java.time.LocalDateTime;

import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.DelayQueue;

/**
 * @author xuanqicheng
 */
@Service
@Slf4j
public class VipExpireServiceImpl implements VipExpireService {

    private static final String CTT = ZoneId.SHORT_IDS.get("CTT");

    @Autowired
    private UserVipDao userVipDao;

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private MakeFriendsMessage makeFriendsMessage;

    private DelayQueue<DelayMessage> queue = new DelayQueue<>();

    /**
     *
     * @return
     */
    @Override
    public DelayQueue<DelayMessage> getVipExpireQueueInit() {
        List<UserVip> userVipList = userVipDao.selectUserVipInfoByStatus(VipStatusType.EFFECTIVE_TYPE.getCode());
        log.info("初始化化vip开始");
        for(UserVip userVip : userVipList){
            if(userVip.getExpireTime() == null){
                if(userVip.getVipDate()==-1){
                    userVip.setExpireTime(LocalDateTime.now(ZoneId.of(CTT)).plusDays(365));
                }else{
                    userVip.setExpireTime(userVip.getCreateTime().plusDays(userVip.getVipDate()));
                }

                userVipDao.updateUserVipExpireTime(userVip.getUserVipId(),userVip.getExpireTime());
                log.info("初始化化vip更新并更新过期时间：[{}]",userVip);
            }
            DelayMessage<Integer> message = new DelayMessage<>(userVip.getUserVipId(),userVip.getUserVipId(),
                    userVip.getExpireTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
            log.info("初始化vip:"+ JSONObject.toJSONString(message));
            queue.offer(message);
        }
        return queue;
    }

    @Override
    public void putDelayMessage(DelayMessage delayMessage) {
        if(delayMessage!=null){
            queue.offer(delayMessage);
            log.info("将延迟消息放入队列中："+JSONObject.toJSONString(delayMessage));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void vipExpireDataHandler(DelayMessage<Integer> take) throws Exception {

        int userVipId = take.getBody();

        UserVip userVip = userVipDao.getUserVipInfoById(userVipId);
        //userVip 为null代表此用户没有续费,进行过期操作
        if(userVip !=null){
            LocalDateTime localDateTime = LocalDateTime.now();
            if(localDateTime.isAfter(userVip.getExpireTime())
                    ||localDateTime.equals(userVip.getExpireTime())){
                //修改user vip状态
                userVipDao.updateUserVipStatusByUserVipId(userVipId);
                //修改用户vip状态,

                if(VipType.COMMON_VIP_TYPE.getCode()==userVip.getVipType()){
                    //修改普通vip状态
                    userInfoDao.updateUserIsVip(2, userVip.getUserId());
                }else if(VipType.SUPER_VIP_TYPE.getCode()==userVip.getVipType()){
                    //修改超级vip状态
                    userInfoDao.updateUserIsSVip(Long.parseLong(userVip.getUserId()+""));
                }else if(VipType.PLATINUM_VIP_TYPE.getCode() == userVip.getVipType()){
                    //关闭用户铂金vip状态
                    userInfoDao.updateUserIsPlatinumVipClose(Long.parseLong(userVip.getUserId()+""));
                }

                User user=userInfoDao.getUserInfoByUserId(userVip.getUserId());
                if(user.getIsVip()==2&&user.getIsSVip()==2 && user.getIsPlatinumVip()==2){
                    makeFriendsMessage.sendUserVipType(userVip.getUserId(),2);
                }
            }
        }


    }

//    public static void main(String[] args) {
//        DelayMessage<Integer> message = new DelayMessage<>(12,56,LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() );
//        VipExpireQueueThread v = new VipExpireQueueThread();
//    }


}
